Reorganizing Definitions

Learn how to change the structure of the Terraform definitions and apply the changes.

Our current way of working#

Every resource we’ve defined so far is currently in a different file. That’s a perfectly valid way to use Terraform. It doesn’t really care whether we have one or one thousand files. It concatenates all those with the tf extension.

What makes Terraform unique is its dependency management. No matter how we organize definitions of different resources, it will figure out the dependency tree, and it will create, update, or delete resources in the correct order. That way, we don’t need to bother planning what should be completed first or in which order those resources are defined. That gives us the freedom to work and to organize in a myriad of ways. We, for example, tend to have only three files; one for variables, one for outputs, and one for all the providers and resources. Now let’s try reorganizing the definitions.

Let's move on to reorganizing the definitions

Rearranging Terraform definitions#

  • We’ll start by removing all Terraform definitions.
Removing the existing definitions
  • Next, we’ll concatenate all providers and resources into a single file main.tf.
Concatenating providers and resources

The output is as follows.

Output of the command above
  • Next, we’ll copy the variables. The output is as follows.
Copying and viewing variables
  • Finally, we’ll copy the outputs as well. The output is as follows.

Output of cat output.tf

That’s it. Everything we need to create and manage our AKS cluster is now neatly organized. It’s split into main.tf (which contains all the modules and resources), variables.tf, and output.tf.

To demonstrate that Terraform doesn’t care how we organize the definitions nor their order, we’ll apply them again.

terraform apply

The output, limited to the relevant parts, is as follows.

Output of the command above

As we can see, there is nothing to add, change, or destroy. We didn’t change any of the definitions. We only reorganized them.

Try it yourself#

You can try all of the commands used in this lesson in the code playground below. Press the “Run” button and wait for a few seconds for it to connect.

For ease of use, all of the commands above are combined in main.sh.

Please provide values for the following:
AZURE_BUCKET_NAME
Not Specified...
/
main.sh
files
backend.tf
k8s-control-plane.tf
output.tf
provider.tf
storage.tf
variables.tf
Code playground

Dealing with a Bug That Prevents Upgrade of Node Pools

Destroying the Resources